﻿//
// Created by QU on 24-9-28.
//

#ifndef SINGLETON_H
#define SINGLETON_H

#include <memory>
#include <mutex>

template <typename T>
class Singleton
{
public:
    Singleton(const Singleton&) = delete;
    Singleton& operator=(const Singleton&) = delete;

    template <typename... Args>
    static std::shared_ptr<T> getInstance(Args&&... args)
    {
        // 使用自定义 deleter 来确保私有析构函数可用
        std::call_once(m_flag, [&](Args&&... inner_args)
        {
            m_shared_instance = std::shared_ptr<T>(new T(std::forward<Args>(inner_args)...), [](const T* ptr)
            {
                delete ptr;
            });
        }, std::forward<Args>(args)...);

        return m_shared_instance;
    }

protected:
    Singleton() = default;
    ~Singleton() = default;

private:
    inline static std::shared_ptr<T> m_shared_instance;
    inline static std::once_flag m_flag;
};

#endif // SINGLETON_H
